<template>
  <div class="blogs">
    <div class="content-header">
      <h1>用户管理<small>个人信息</small></h1>
      <el-breadcrumb separator-class="el-icon-arrow-right" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">后台管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>个人信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!--中间内容-->
    <div class="app-container">
      <div class="box">
        <div class="t-mask" id="t_mask" v-show="show"></div>
        <div class="verity" v-show="show" >
          <div style="font-size: 22px;font-family:-apple-system;position: relative;top: -3px;" >拖动下方滑块完成拼图</div>
          <div class="close" @click="padlock()" style="width: 31px;height: 31px;color: #555;position: relative;left: 280px;top: -40px;">
            <div class="el-icon-close" style="font-size: 30px;"> </div>
          </div>
          <slide-verify
                        ref="slideblock"
                        @again="onAgain"
                        @fulfilled="onFulfilled"
                        @success="onSuccess"
                        @fail="onFail"
                        @refresh="onRefresh"
                        :accuracy="accuracy"
                        :slider-text="text"
          ></slide-verify>
          <div style="color: red;padding-top: 5px">{{msg}}</div>
        </div>
        <el-form :model="formData" :rules="userRules" ref="userForm" label-width="100px">
          <el-row>
            <el-col :span="8">
              <el-form-item prop="username" label="用户名">
                <el-input v-model="formData.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="password" label="密码">
                <el-input v-model="formData.password"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item prop="phone" label="手机号">
                <el-input v-model="formData.phone" ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="verify" label="验证码">
                <el-input style="width: 340px" v-model="formData.verify"></el-input>
                <el-button style="float: right"
                  @click.native.prevent="bindforgetSendCode"
                  class="codebtn"
                  :disabled="disabled"
                >{{ btnText }}</el-button>
              </el-form-item>
            </el-col>
          </el-row>
            <el-form-item prop="avatar" label="头像地址">
              <div style="height: 100px">
              <el-input style="width: 78%" v-model="formData.avatar" v-on:input="contentOrder"></el-input>
              </div>
              <el-upload
                class="avatar-uploader"
                action="/service-user/user/updateAvatar"
                multiple
                :limit="1"
                :on-exceed="masterFileMax"
                :show-file-list="false"
                :http-request="uploadPic"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src=this.imageUrl class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          <el-form-item>
            <el-button type="primary" @click.native.prevent="submitForm"  :disabled="disabled2">{{ btnText2 }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <br>
    <br>
  </div>
</template>

<script>

export default {
  data () {
    return {
      user: {},
      show: false,
      msg: '',
      text: '向右滑',
      // 精确度小，可允许的误差范围小；为1时，则表示滑块要与凹槽完全重叠，才能验证成功。默认值为5
      accuracy: 5,
      phone: '',
      imageUrl: '',
      formData: {
        uid: '',
        username: '',
        password: '',
        phone: '',
        avatar: '',
        verify: ''
      },
      userRules: {
        // 验证用户名是否合法
        username: [
          { required: true, message: '请输入登录名称', trigger: 'blur' },
          { min: 3, max: 15, message: '长度在 3 到 15 个字符', trigger: 'blur' }
        ],
        // 验证密码是否合法
        password: [
          // { required: true, message: '请输入登录密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
        ],
        verify: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { min: 6, max: 6, message: '验证码为6个字符', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '请输入头像地址', trigger: 'blur' },
          { min: 1, max: 150, message: '长度在 1 到 150 个字符', trigger: 'blur' }
        ],
        phone: [
          // { required: true, message: '请输入头像地址', trigger: 'blur' },
          { min: 11, max: 11, message: '请输入正确的手机号码', trigger: 'blur' }
        ]
      },
      //验证码
      btnText: "获取验证码",
      btnText2: "立即修改",
      disabled: false,
      disabled2: false,
      Message: ''
    }
  },
  created () {
    this.getUser()
  },
  methods: {
    /***
     * 滑动验证码方法区
     */
    //滑动验证通过
    onSuccess(times){
      this.show=!this.show
      this.handleClick()
      this.msg=''
      const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if(reg.test(this.formData.phone)){
        this.$message.success('验证通过，耗时:'+(times / 1000).toFixed(1) + '秒,发送短信验证码中.....')
        this.$http.post("/service-user/user/SendMessage/"+this.phone).then((res) => {
          if(res.data.flag){
            this.$message.error("短信验证码发送成功!")
            this.Message=res.data.phone;
            this.disabled = true;
            this.btnText = "请稍候...";
            alert(this.Message)
            setTimeout(() => {
              this.doLoop(60);
            }, 500);
          }else{
            this.$message.error(res.data.error)
          }
        })
      }else{
        this.$message.error("请输入正确的手机号码!")
      }
    },contentOrder(){
      this.imageUrl=this.formData.avatar
    },
    //关闭弹窗事件
    padlock(){
      this.handleClick()
      this.show=!this.show
    },
    //滑动验证不通过
    onFail(){
      let this_=this;
      this.msg=('请控制拼图块对齐缺口!')
      setTimeout(function() {
        this_.msg=''
      }, 1500)
    },
    onRefresh(){
      console.log('点击了刷新小图标');
      this.msg = ''
    },
    onFulfilled() {
      console.log('刷新成功啦！');
    },
    onAgain() {
      console.log('检测到非人为操作的哦！');
      this.msg = 'try again';
      // 刷新
      this.$refs.slideblock.reset();
    },
    handleClick() {
      // 父组件直接可以调用刷新方法
      this.$refs.slideblock.reset();
    },
    // 发送验证码
    bindforgetSendCode() {
      this.show=!this.show
    },
    // 手机验证码的倒计时
    doLoop: function (seconds) {
      seconds = seconds ? seconds : 60;
      this.btnText = seconds + "s后获取";
      let countdown = setInterval(() => {
        if (seconds > 0) {
          this.btnText = seconds + "s后获取";
          --seconds;
        } else {
          this.btnText = "获取验证码";
          this.disabled = false;
          clearInterval(countdown);
        }
      }, 1000);
    },
    // 手机验证码的倒计时
    do2Loop: function (seconds) {
      seconds = seconds ? seconds : 60;
      this.btnText2 = seconds + "s后修改";
      let countdown = setInterval(() => {
        if (seconds > 0) {
          this.btnText2 = seconds + "s后修改";
          --seconds;
        } else {
          this.btnText2 = "获取验证码";
          this.disabled2 = false;
          clearInterval(countdown);
        }
      }, 1000);
    },
    masterFileMax (files, fileList) {
      console.log(files, fileList)
      this.$message.warning('请最多上传一张图片')
    },
    async uploadPic (param) {
      var fileObj = param.file
      var form = new FormData()
      // 文件对象
      form.append('file', fileObj)
      this.$http.post('/service-user/user/updateAvatar/'+this.user.uid,form).then((res) => {
        if (res.data.flag) {
          // 弹出提示信息
          this.formData.avatar = res.data.fileName
          this.imageUrl=res.data.fileName
          console.log(this.formData)
          let this_=this;
            this_.$message.success('上传头像成功')
        } else { // 执行失败
          this.$message.error(res.message)
        }
      })

    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt5M) {
        this.$message.error('上传头像图片大小不能超过5MB!')
      }
      return isJPG && isLt5M
    },
    submitForm () {
      // 进行表单校验
      this.$refs.userForm.validate((valid) => {
        const reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
        if (valid) {
          //验证手机号码是否合法
          if(reg.test(this.formData.phone)){
          if(this.formData.verify===this.Message){
              // 表单校验通过，发ajax请求，把数据录入至后台处理
              const param = this.formData
              this.$http.put('/service-user/user/update', param).then((res) => {
                // 关闭新增窗口
                if (res.data.flag) {
                  setTimeout(() => {
                    this.do2Loop(180);
                  }, 500);
                  this.disabled2 = true;
                  // 弹出提示信息
                  this.$message({
                    message: '修改成功,请重新登录！',
                    type: 'success'
                  })
                  this.setlogin()
                } else { // 执行失败
                  this.$message.error(res.data.message)
                }
              })
            }else{//短信验证码错误!
            this.$message.error('短信验证码错误,请重新输入!')
            return false
            }
          }else{//手机号码非法!
            this.$message.error("请输入正确的手机号码!")
            return false
          }
        } else { // 校验不通过
          this.$message.error('校验失败，请检查输入格式')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    getUser () {
      this.user =JSON.parse(window.sessionStorage.getItem('user'))
      if (this.user!= null) {
        this.formData.uid = this.user.uid
        this.formData.avatar =this.user.avatar
        this.formData.username = this.user.username
        this.formData.phone = this.user.phone
        this.phone = this.user.phone
        this.password=this.user.password
      }else{
        this.$message.error("请先登录账号! 正在跳转登录页面......")
        this.$router.push('/login')
        setTimeout(() => {
          window.location.reload()
        }, 500)
      }
    },
    setlogin(){
      sessionStorage.setItem("user",null)
      window.sessionStorage.setItem('token',null)
      this.user=null;
      this.$router.push({ path: "/login/"});
    }
  }
}
</script>

<style lang="less" scoped>
.avatar-uploader {
  width:180px;
  height: 180px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.verity{
  user-select: none;
  position:absolute;
  border-radius: 5px;
  background-color: #fff;
  padding-top: 35px;
  padding-left: 10px;
  width: 335px;
  height: 354px;
  border: 1px solid #d4d4d5;
  left:40%;
  top: 30%;
  z-index: 2000000002;
}
.t-mask{
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: #000;
  opacity: .5;
  z-index: 2000000000;
}
.close:hover{
  cursor: pointer;
}
//关闭按钮样式
  @import "../../../assets/css/me.css";
</style>
